# -*- coding: utf-8 -*-
#
import socket   
import click
import sys
import array
import time
import serial

def sock_writer(sock, conn):
    def writer(b: bytes):
        sock.sendto(b, conn)
    return writer

def ser_writer(ser):
    def writer(b: bytes):
        ser.write(b)
    return writer


def send_str(writer):
    while 1:
        print('Please input your context:')
        buf = input().encode('utf-8')

        if buf != '':
            b=array.array('B', buf)
            writer(b)

        if (buf == 'exit'):
            sys.exit()

def send_file(writer, files, repeat_n, send_unit, delay_time):
    for filename in files:
        with open(filename) as f:
            buf = f.read()
            buf_len = len(buf)
            for i in range(repeat_n):
                print("Sending file %s for %d time"%(filename, i))
                start = 0
                size = send_unit
                while start < buf_len:
                    if start + send_unit > buf_len:
                        size = buf_len - start
                    else:
                        size = send_unit
                    # sock.sendto(bytes(buf[start:start+size].encode('utf-8')), conn)
                    writer(bytes(buf[start:start+size].encode('utf-8')))
                    if delay_time > 0.01:
                        time.sleep(delay_time)
                    start = start + size

@click.group(help="发送字符串或文件，如果没有指定文件，表示手动输入")
def cli():
    pass

@cli.command(help="UDP发送字符串或文件")
@click.option("--addr", default="127.0.0.1")
@click.option("--port", type=click.INT, default=10010)
@click.option("-n", type=click.INT, default=100, help="重复发送文件的次数")
@click.option("--delay", "-d", type=click.FLOAT, default=0.1, help="发送间隔,单位秒")
@click.option("--unit", "-u", type=click.INT, default=512, help="单次发送块大小,单位字节")
@click.argument("files", nargs=-1)
def udp(addr, port, n, delay, unit, files):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    addr_conn = (addr, port)
    print(f"===Sending UDP to {addr_conn} {files}")

    w = sock_writer(sock, addr_conn)
    if files:
        send_file(w, files, n, unit, delay)
    else:
        send_str(w)

@cli.command(help="串口发送字符串或文件")
@click.option("--port", default="/dev/pts/11")
@click.option("-n", type=click.INT, default=100, help="重复发送文件的次数")
@click.option("--delay", "-d", type=click.FLOAT, default=0.1, help="发送间隔,单位秒")
@click.option("--unit", "-u", type=click.INT, default=128, help="单次发送块大小,单位字节")
@click.argument("files", nargs=-1)
def ser(port, n, delay, unit, files):
    ser = serial.Serial(port, 115200, timeout=0.5)
    if ser.isOpen():
        print(f"Open {port} success")
    else:
        print(f"Open {port} failed")

    w = ser_writer(ser)
    if files:
        send_file(w, files, n, unit, delay)
    else:
        send_str(w)

if __name__ == '__main__':   
    cli()